﻿@model Nop.Plugin.Payments.Worldpay.Models.PaymentInfoModel
@{
    Layout = "";
    Html.AddScriptParts(ResourceLocation.Footer, "https://gwapi.demo.securenet.com/v1/PayOS.js");
}
@inject Nop.Core.IWorkContext workContext
@inject WorldpayPaymentSettings worldpayPaymentSettings
@inject Nop.Core.Domain.Orders.OrderSettings orderSettings

<script type="text/javascript">
    $(document).ready(function () {
        $('#@Html.IdFor(model => model.StoredCardId)').change(toggleStoredCard);
        toggleStoredCard();

        var submitForm = false;
        var errorsExist = false;
        var stepBack = false;
        var onePageCheckout = @orderSettings.OnePageCheckoutEnabled.ToString().ToLower();
        $('.payment-info-next-step-button').attr('onclick', null);

        function tokenize() {
            var token = tokenizeCard({
                'publicKey': '@worldpayPaymentSettings.PublicKey',
                'card':
                {
                    'number': $('#@Html.IdFor(model => model.CardNumber)').val(),
                    'cvv': $('#@Html.IdFor(model => model.CardCode)').val(),
                    'creditCardType': $('#@Html.IdFor(model => model.CardType)').val(),
                    'expirationDate': ('0' + $('#@Html.IdFor(model => model.ExpireMonth)').val()).slice(-2) + '/' + $('#@Html.IdFor(model => model.ExpireYear)').val(),
                    'emailReceipt': @((!string.IsNullOrEmpty(workContext.CurrentCustomer.BillingAddress?.Email)).ToString().ToLower()),
                    'email': '@workContext.CurrentCustomer.BillingAddress?.Email',
                    'firstName': '@workContext.CurrentCustomer.BillingAddress?.FirstName',
                    'lastName': '@workContext.CurrentCustomer.BillingAddress?.LastName',
            @if (worldpayPaymentSettings.ValidateAddress)
            {
                <text>
                    'address':
                    {
                        'line1': '@workContext.CurrentCustomer.BillingAddress?.Address1',
                        'city': '@workContext.CurrentCustomer.BillingAddress?.City',
                        'state': '@workContext.CurrentCustomer.BillingAddress?.StateProvince?.Abbreviation',
                        'country': '@workContext.CurrentCustomer.BillingAddress?.Country?.TwoLetterIsoCode',
                        'zip': '@workContext.CurrentCustomer.BillingAddress?.ZipPostalCode',
                        'company': '@workContext.CurrentCustomer.BillingAddress?.Company',
                        'phone': '@workContext.CurrentCustomer.BillingAddress?.PhoneNumber'
                    }
                </text>
            }
                },
                'developerApplication':
                {
                    'developerId': '@(worldpayPaymentSettings.UseSandbox ? WorldpayPaymentDefaults.SandboxDeveloperId : WorldpayPaymentDefaults.DeveloperId)',
                    'version': '@(worldpayPaymentSettings.UseSandbox ? WorldpayPaymentDefaults.SandboxDeveloperVersion : WorldpayPaymentDefaults.DeveloperVersion)'
                }
            }).done(function (result) {
                var response = $.parseJSON(JSON.stringify(result));
                if (response.success) {
                    $('#@Html.IdFor(model => model.Token)').val(response.token);
                } else {
                    $('#@Html.IdFor(model => model.Errors)').val(response.message);
                    errorsExist = true;
                }
                submitForm = true;
                $('input.payment-info-next-step-button').click();
            }).fail(function () {
                $('#@Html.IdFor(model => model.Errors)').val('Failed to get payment token');
                errorsExist = true;
                submitForm = true;
                $('input.payment-info-next-step-button').click();
            });
        }

        $('input.payment-info-next-step-button').on('click', function (data) {
            var selectedStoredCardId = $('#@Html.IdFor(model => model.StoredCardId)').val()
            if (!submitForm && (!selectedStoredCardId || selectedStoredCardId == '@Guid.Empty.ToString()')) {
                if (!errorsExist && !stepBack) {
                    tokenize();
                }
                return false;
            }
            else if (onePageCheckout) {
                submitForm = false;
                PaymentInfo.save();
            }
        });

        $(document).on('accordion_section_opened', function (data) {
            if (data && (data.currentSectionId == 'opc-billing' || data.currentSectionId == 'opc-shipping' || data.currentSectionId == 'opc-shipping_method' || data.currentSectionId == 'opc-payment_method')) {
                stepBack = true;
            }
        });
    });

    function toggleStoredCard() {
        var selectedStoredCardId = $('#@Html.IdFor(model => model.StoredCardId)').val();
        if (!selectedStoredCardId || selectedStoredCardId == '@Guid.Empty.ToString()') {
            $('#worldpay-card-details').show();
        } else {
            $('#worldpay-card-details').hide();
        }
    }
</script>

<input type="hidden" asp-for="Token">
<input type="hidden" asp-for="Errors">

@if (!Model.IsGuest && Model.StoredCards.Any())
{
    <table width="100%" cellspacing="2" cellpadding="1" border="0">
        <tr>
            <td>
                <label asp-for="StoredCardId">@T("Plugins.Payments.Worldpay.Fields.StoredCard"):</label>
            </td>
            <td>
                <select asp-for="StoredCardId" asp-items="Model.StoredCards" class="dropdownlists"></select>
            </td>
        </tr>
    </table>
}

<table width="100%" cellspacing="2" cellpadding="1" border="0" id="worldpay-card-details">
    <tr>
        <td>
            &nbsp;
        </td>
        <td>
            <img src="@Url.Content("~/Plugins/Payments.Worldpay/cards.jpg")" alt="" />
        </td>
    </tr>
    <tr>
        <td>
            <label asp-for="CardType">@T("Payment.SelectCreditCard"):</label>
        </td>
        <td>
            <select asp-for="CardType" asp-items="Model.CardTypes" class="dropdownlists"></select>
        </td>
    </tr>
    <tr>
        <td>
            <label asp-for="CardNumber">@T("Payment.CardNumber"):</label>
        </td>
        <td>
            <input type="text" asp-for="CardNumber" style="width:165px;" autocomplete="off" maxlength="22" />
            <span asp-validation-for="CardNumber"></span>
        </td>
    </tr>
    <tr>
        <td>
            <label asp-for="ExpireMonth">@T("Payment.ExpirationDate"):</label>
        </td>
        <td>
            <select asp-for="ExpireMonth" asp-items="Model.ExpireMonths"></select>
            /
            <select asp-for="ExpireYear" asp-items="Model.ExpireYears"></select>
        </td>
    </tr>
    <tr>
        <td>
            <label asp-for="CardCode">@T("Payment.CardCode"):</label>
        </td>
        <td>
            <input type="text" asp-for="CardCode" style="width:60px;" autocomplete="off" maxlength="4" />
            <span asp-validation-for="CardCode"></span>
        </td>
    </tr>
    @if (!Model.IsGuest)
    {
        <tr>
            <td>
                <label asp-for="SaveCard">@T("Plugins.Payments.Worldpay.Fields.SaveCard"):</label>
            </td>
            <td>
                <input type="checkbox" asp-for="SaveCard" />
                <span asp-validation-for="SaveCard"></span>
            </td>
        </tr>
    }
</table>